package com.fesine.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.fesine.commons.util.CryptographyUtil;
import com.fesine.commons.util.DateUtils;
import com.fesine.commons.util.GenerateUUID;
import com.fesine.commons.util.ResponseUtils;
import com.fesine.learn.po.UserInfoPo;
import com.fesine.learn.service.UserInfoService;


/**
 * 用户信息请求处理
 */
@Controller 
@RequestMapping("/userInfo")
public class UserInfoController {
		
	private static final Logger logger = Logger.getLogger(UserInfoController.class);

	@Autowired
	private UserInfoService userInfoService;

	public static long initTime; 
	public static long loginTime;

	@Value("${upload.file.root}") 
	private String uploadFileRoot;
	
	/**
	*登录操作
	*/
	 @RequestMapping(value = "/login", method = RequestMethod.POST)
	    public void login(HttpServletRequest req, HttpServletResponse response) {
	        Map<String, Object> map = new HashMap<>();
	        loginTime = System.currentTimeMillis();
	        if (loginTime - initTime > 30000) {
	            map.put("success", false);
	            map.put("msg", "验证码过期，有效时间30秒!");
	        } else {
	            String userName = req.getParameter("userName");
	            String captchaToken = ((String) req.getSession().getAttribute("captchaToken")).toLowerCase();
	            String checkCode = req.getParameter("checkCode").toLowerCase();
	            logger.info("----->captchaToken:" + captchaToken + ",checkCode:" + checkCode);
	            //不区分大小写
	            if (!captchaToken.equals(checkCode.toLowerCase())) {
	                map.put("success", false);
	                map.put("msg", "验证码错误!");
	            } else {
	                UserInfoPo userInfoPo = new UserInfoPo();
	                userInfoPo.setUserName(userName);
	                userInfoPo = userInfoService.getUserInfo(userInfoPo);
	                if (userInfoPo != null) {
	                    //用户名正确，再验证密码
	                    String password = req.getParameter("password");
	                    if (CryptographyUtil.md5(password, "fesine").equals(userInfoPo.getPassword())) {
	                        //创建用户session
	                        req.getSession().setAttribute("userName", userName);
	                        req.getSession().setAttribute("nickName", userInfoPo.getNickName());
	                        req.getSession().setAttribute("uploadFileRoot", uploadFileRoot);
	                        map.put("success", true);
	                        map.put("msg", "验证成功!");
	                    } else {
	                        map.put("success", false);
	                        map.put("msg", "密码错误!");
	                    }
	                } else {
	                    map.put("success", false);
	                    map.put("msg", "用户名不存在!");
	                }
	            }
	        }
	        try {
	            ResponseUtils.outPut(response, map);
	        } catch (Exception e) {
	            logger.error("", e);
	        }
	    }

		
	/**
	 *退出登录
	*/
	@RequestMapping("/logout")
	public void logout(HttpServletRequest req, HttpServletResponse response)throws Exception { 
		
		req.getSession().invalidate();
		Map<String, Object> map = new HashMap<>(); 
		map.put("success", true);
		map.put("msg", "注销成功!"); 
		try{
			ResponseUtils.outPut(response, map);
		}catch(Exception e){
			logger.error("",e);
		}
		
		}


	/**
	 *添加用户信息
	*/
	@RequestMapping(value = "/addUserInfo", method = RequestMethod.POST)
	public void addUserInfo(@RequestParam MultipartFile photos, HttpServletRequest req, HttpServletResponse response)throws Exception {

		UserInfoPo u = createUserInfo(req); 
		u.setId(GenerateUUID.getUUId()); 
		Date date = new Date(); 
		u.setCreateTime(date); 
		u.setUpdateTime(date);

		Map<String, Object> map = new HashMap<>(); 
		map.put("success", true); 
		map.put("msg", "添加用户信息成功!"); 
		try {

			if (photos.isEmpty()) {
				logger.info("--->没有上传头像"); 
				u.setHeadPhoto("default.jpg");
		} else {
			String headPhoto = uploadPhotos(photos, req); 
			u.setHeadPhoto(headPhoto);
			}
			
			userInfoService.addUserInfo(u);
			
		} catch (Exception e) { 
			logger.error("", e);
			map.put("success", false); 
			map.put("msg", "添加 用户信息失败!");
			}
		try{
			ResponseUtils.outPut(response, map);
		}catch(Exception e){
			logger.error("",e);
		}

		}

	/**
	 *修改用户信息
	*/
	@RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
	public void updateUserInfo(@RequestParam MultipartFile photos,HttpServletRequest req, HttpServletResponse response)throws Exception {
		
		UserInfoPo u = createUserInfo(req); 
		Date date = new Date(); 
		
		u.setUpdateTime(date);

		Map<String, Object> map = new HashMap<>(); 
		map.put("success", true); 
		map.put("msg", "修改 用户信息成功!"); 
		try {
			if (!photos.isEmpty()){
				String headPhoto = uploadPhotos(photos, req); 
				u.setHeadPhoto(headPhoto);
				}
			userInfoService.modifyUserInfo(u);

		} catch (Exception e) { 
			logger.error("", e);
			map.put("success", false); 
			map.put("msg", "修改用户信息失败!");
			}
		try{
			ResponseUtils.outPut(response, map);
		}catch(Exception e){
			logger.error("",e);
		}
	
		}

	/**
	 *修改用户信息2
	*/
	@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
	public void updatePassword(HttpServletRequest req, HttpServletResponse response)throws Exception {

		UserInfoPo u = createUserInfo(req); 
		Date date = new Date(); 
		u.setUpdateTime(date);

		Map<String, Object> map = new HashMap<>(); 
		map.put("success", true);
		map.put("msg", "修改密码成功!"); 
		try {
			userInfoService.modifyUserInfo(u);
			} catch (Exception e) { 
				logger.error("", e);

				map.put("success", false); 
				map.put("msg", "修改密码失败!");
				}
		try{
			ResponseUtils.outPut(response, map);
		}catch(Exception e){
			logger.error("",e);
		}

		}

	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public void uploadFile(@RequestParam MultipartFile photos, HttpServletRequest req,HttpServletResponse response){ 
		Map<String, Object> map = new HashMap<>(); 
		map.put("success", true);
		map.put("msg", "上传 文件成功!"); 
		try {

			String headPhoto = this.uploadPhotos(photos,req); 
			map.put("fileName", headPhoto);
			} catch (IOException e) { 
				logger.error("",e);

				map.put("success", false); 
				map.put("msg", "上传文件失败!");
				}
		try{
			ResponseUtils.outPut(response, map);
		}catch(Exception e){
			logger.error("",e);
		}

		}
	
	/**
	 *删除 用户信息
	 */
	@RequestMapping(value = "/deleteUserInfo", method = RequestMethod. POST)
	public void deleteUserInfo(HttpServletRequest req, HttpServletResponse response)throws Exception {

		Map<String, Object> map = new HashMap<>();

		String userIds = req.getParameter("userIds").replace("\"", ""); 
		String[] IdsArr = userIds.split(",");

		map.put("success", true); 
		map.put("msg", "删除用户信息成功!"); 
		try {
			userInfoService.deleteUsers(IdsArr);

			} catch (Exception e) { 
				logger.error("", e);

				map.put("success", false); 
				map.put("msg", "删除用户信息失败!");
				}
		try{
			ResponseUtils.outPut(response, map);
		}catch(Exception e){
			logger.error("",e);
		}
		
		}

	/**
	 *查询 用户信息
	 */
	@RequestMapping("/listUserInfo")
	public void listUserInfo(HttpServletRequest req, HttpServletResponse response)throws Exception {

		UserInfoPo u = createUserInfo(req); 
		String pageNo = req.getParameter("page"); 
		String pageSize = req.getParameter("limit");
		
		
		Map<String, Object> map = new HashMap<>(); 
		map.put("success", true); 
		map.put("msg", "查询用户信息成功!"); 
		//list = userInfoService.listUserInfo(u,Integer.parseInt(pageNo));
		try {
			List<UserInfoPo> list;
			if (!StringUtils.isEmpty(pageNo) && !StringUtils.isEmpty(pageSize)) { 
				list = userInfoService.listUserInfo(u, Integer.parseInt(pageNo), Integer.parseInt(pageNo)); 
				}else{
					list = userInfoService.listUserInfo(u); 
				}
			
			int total = userInfoService.getTotal(u); 
			map.put("userInfoList", list);
			map.put("total", total);
			} catch (Exception e) { 
				logger.error("", e);

				map.put("success", false); 
				map.put("msg", "查询用户信息失败!");
				}
		try{
			ResponseUtils.outPut(response, map);
		}catch(Exception e){
			logger.error("",e);
		}
		
		}

	/**
	*将前端请求字段转换为UserInfoPo对象
	*/

	private UserInfoPo createUserInfo(HttpServletRequest req) { 
		UserInfoPo u = new UserInfoPo(); 
		u.setId(req.getParameter("id")); 
		u.setUserName(req.getParameter("userName"));

		if (!StringUtils.isEmpty(req.getParameter("password")))

			u.setPassword(CryptographyUtil.md5(req.getParameter("password" ), "fesine"));
		u.setSex(req.getParameter("sex"));
		u.setNickName(req.getParameter("nickName")); 
		u.setCellPhone(req.getParameter("cellPhone")); 
		u.setAddress(req.getParameter("address")); 
		u.setHeadPhoto(req.getParameter("headPhoto")); 
		u.setInfoDesc(req.getParameter("infoDesc")); 
	
		return u;

	}

	/**
	 *上传头像 文件
	 */
	private String uploadPhotos(MultipartFile photos, HttpServletRequest req) throws IOException {

		String headPhoto;

		String fileName = DateUtils.formatDate(new Date(), "yyyyMMddHHmmsssss");

		String root = ResponseUtils.getRootPath(req); 
		String filePath = root + uploadFileRoot;

		String orgFileName = photos.getOriginalFilename();//源 文件名 
		String fileType = orgFileName.substring(orgFileName.lastIndexOf(".") + 1);

		fileName = "[" + fileType + "]" + fileName + "." + fileType; 
		filePath = filePath + fileName; 
		logger.info("--->上传 文件路路径:" + filePath);

		long startTime = System.currentTimeMillis(); //获取开始时间 
		try {
			//执 行行上传动作 
			photos.transferTo(new File(filePath)); 
			headPhoto = fileName;
			long endTime = System.currentTimeMillis(); //获取结束时间
			logger.info("上传文件共使用时间：" + (endTime - startTime) + "毫秒"); 
			return headPhoto;
			
		} catch (Exception e) { 
			logger.error(" 文件上传失败", e); 
			throw e;
			}
		}

}
